<template>
  <div class="project-file-container">
    <h2 v-if="mode === 'edit'">项目文档库</h2>
    <div class="content">
      <div class="btn-group">
        <div :style="{'visibility':fileMode==='dir'?'visible':'hidden'}"
             class="edit-btn">
          <el-upload class="company-logo-upload"
                     ref="uploadFile"
                     :http-request="uploadFile"
                     action
                     :show-file-list="false"
                     :limit="20"
                     :multiple="true"
                     :auto-upload="false"
                     :file-list="fileList"
                     :on-success="handleFileSuccess"
                     :on-change="handleFileChange"
                     :on-exceed="handleFileExceed"
                     :before-upload="beforeFileUpload">
            <el-button class="upload"
                       size="small"
                       icon="el-icon-top"
                       type="primary">上传</el-button>
          </el-upload>
          <el-button class="download"
                     size="small"
                     @click="batchDownload"
                     icon="el-icon-bottom">下载</el-button>
          <el-button class="delete"
                     size="small"
                     @click="batchDelete"
                     icon="el-icon-delete">删除</el-button>
        </div>
        <div class="search-btn">
          <el-input v-model="requestParam.file_alias"
                    size="small"
                    @keyup.enter.native="searchFile"
                    placeholder="请输入文件名或标签">

          </el-input>
          <el-button @click="searchFile"
                     type="primary"
                     size="small"
                     icon="el-icon-search">查询</el-button>
          <el-button size="small"
                     @click="reset"
                     icon="el-icon-refresh-left">
            重置
          </el-button>
        </div>
        <!-- <el-button @click="editTagDialogVisible = true">设置标签</el-button> -->

      </div>
      <span class="tip">提示：通过鼠标右键可以进行文件或文件夹的新建、修改、删除。</span>

      <div class="file-content">
        <div v-if="!isSearch"
             class="tree-container">
          <div class="tab-btn-container">
            <div class="tab-btn dir"
                 @click="toggleFileMode('dir')"
                 :class="{ active: fileMode === 'dir' }">
              按文件夹查看
            </div>
            <div class="tab-btn tag"
                 @click="toggleFileMode('tag')"
                 :class="{ active: fileMode === 'tag' }">
              按标签查看
            </div>
          </div>
          <FileTree @callback="editNodeCb"
                    v-if="fileMode === 'dir'"
                    :mode="mode"
                    :projectId="projectId"
                    :curMenu.sync="choosedTreeNode"></FileTree>
          <TagList ref="tagList"
                   :choosedTag.sync="choosedTag"
                   v-if="fileMode === 'tag'"></TagList>
        </div>
        <div :style="{'left':isSearch?0:'370px'}"
             class="table-container">
          <el-table class="file-table"
                    ref="fileTable"
                    :data="fileListData.list">
            <el-table-column width="40">
              <template slot-scope="scope">
                <el-checkbox @change="checked => {selectChange(checked, scope.row);}"
                             v-model="scope.row.checked"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="file_alias"
                             label="文件名称">
              <template slot-scope="scope">
                <div class="edit-input">
                  <el-input v-if="scope.row.edit"
                            v-model="scope.row.file_alias"
                            placeholder="请输入文件名">
                  </el-input>

                  <span v-else>{{ scope.row.file_alias }}</span>
                  <div class="icon-container"
                       v-if="scope.row.edit">
                    <i v-if="scope.row.edit"
                       @click="cancelEdit(scope.row)"
                       class="el-icon-close cancel"></i>
                    <i v-if="scope.row.edit"
                       @click="confirmEdit(scope.row)"
                       class="el-icon-check confirm"></i>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="file_size"
                             label="大小">
              <template slot-scope="scope">
                <span>{{ scope.row.file_size + "M" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updated_at"
                             label="修改时间">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-if="['mp4','wmv','avi','rmvb','docx','doc','xls','xlsx','jpg','jpeg','png'].includes(scope.row.file_ext)"
                           @click="lookFile(scope.row)"
                           type="text">预览</el-button>
                <el-button @click="editFile(scope.row)"
                           type="text">修改</el-button>
                <el-button @click="downloadFile(scope.row)"
                           type="text">下载</el-button>
                <el-button @click="deleteFile(scope.row)"
                           type="text">删除</el-button>
                <el-button @click="editFileTag(scope.row)"
                           type="text">
                  设置文件标签
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 视频预览 -->
    <el-dialog title="视频预览"
               :visible.sync="dialogvideo"
               width="50%">
      <video controls="controls"
             class="videoLoc"
             :src="videoUrl"></video>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogvideo = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="'正在上传(' + uploadFileIndex + '/' + uploadQuene.length + ')'"
               :modal="mode === 'edit'"
               width="768px"
               @close="uploadDialogClose"
               :visible.sync="uploadQueneDialogVisible">
      <ul class="upload-quene-list">
        <li class="upload-quene-item"
            v-for="(item, index) in uploadQuene"
            :key="index">
          <span class="file-name">
            <img src="@/assets/file-icon.png"
                 alt="" />
            <i>{{ item.name }}</i>
          </span>
          <span class="file-size">{{ item.file_size }}</span>
          <span class="dir-name">{{ choosedTreeNode.dir_name }}</span>
          <span v-if="item.status !== 'resolve'"
                class="staus">{{
            item.percent
          }}</span>
          <span class="status"
                v-if="item.status === 'resolve'">
            <i class="fa fa-check-circle"></i>
          </span>
        </li>
      </ul>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="closeDialog"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <EditTagDialog :dialogVisible.sync="editTagDialogVisible"
                   :fileId="choosedFile.p_project_doc_file_id"
                   :fileSign="fileSign"
                   :dialogStatus="'addFileTag'"
                   @callback="editTagCb"></EditTagDialog>
    <!-- 预览 -->
    <PreviewDialog v-if="viewDialog==true"
                   :viewDialog.sync="viewDialog"
                   :url.sync="url"></PreviewDialog>
    <!-- <img src="http://dev-consult-new.oss-cn-hangzhou.aliyuncs.com/upload/video/15897933170376/"
         alt=""> -->
  </div>
</template>
<script>
import PreviewDialog from './PreviewDialog';//查看word文档
import OSS from 'ali-oss'
import FileTree from '@/components/FileTree/FileTree'
import { ProjectFileApi } from '@/services/ProjectCenter'
import FileSaver from 'file-saver'
import EditTagDialog from './components/EditTagDialog'
import TagList from './components/TagList'
export default {
  data () {
    return {
      viewDialog: false,//查看word文档的对话框
      url: '',//word文档链接
      dialogvideo: false,
      videoUrl: '',
      fileList: [],
      timerId: 0,
      // 等待上传文件列表
      uploadQuene: [],
      // 当前上传文件在列表中的index
      uploadFileIndex: 0,
      // 当前选中文件树节点
      choosedTreeNode: {},
      // 请求文件列表参数
      requestParam: {
        p_project_dir_id: '',
        file_alias: '',
        file_ext: '',
        tag_id: 0,
        is_delete: 1
      },
      // 文件列表数据
      fileListData: {
        list: [],
        page: 1,
        total_count: 0
      },
      // 上传文件进度弹框是否可见
      uploadQueneDialogVisible: false,
      // 文件id map集合，用于判断指定文件是否已选择
      fileIdMap: new Map(),
      // 已选中文件列表
      choosedFileList: [],
      // 标签模式或文件夹模式
      fileMode: 'dir',
      // 标签库弹框是否可见
      editTagDialogVisible: false,
      // 用户标签列表
      userTagList: [],
      // 当前已选择文件
      choosedFile: [],
      // 标签列表中已选择标签
      choosedTag: 0,
      // 当前文件所属标签
      fileSign: [],
      // 判断是否处于搜索模式，处于搜索模式时，隐藏左侧内容，table占满
      isSearch: false,
      choosedProject: {}
    }
  },
  components: {
    FileTree,
    EditTagDialog,
    TagList,
    PreviewDialog,//预览
  },

  watch: {
    projectId (newval) {
      console.log('newval--->', newval)
    },
    choosedTreeNode: {
      handler (newval) {
        if (newval.p_project_dir_id) {
          this.requestParam.p_project_dir_id = newval.p_project_dir_id
          this.requestParam.tag_id = ''
          this.getProjectFileList()
        }
      },
      deep: true
    },
    choosedTag: {
      handler (newval) {
        this.requestParam.p_project_dir_id = ''
        this.requestParam.tag_id = newval
        this.getProjectFileList()
      },
      deep: true
    },
    '$store.state.choosedProject': function (val) {
      this.choosedProject = val;
      this.getProjectFileTree()
    }
  },
  props: {
    // 区分编辑模式及选择模式
    mode: {
      type: String,
      default: 'edit'
    },
    projectId: {
      type: Number,
      default: 0
    },
    // 输出外部的已选中文件列表
    choosedList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  methods: {
    // 切换模式
    toggleFileMode (type) {
      this.fileMode = type
      this.choosedTag = 0
      this.fileListData.list = []
    },
    // 右上角搜索功能
    searchFile () {
      if (this.requestParam.file_alias === '') {
        this.isSearch = false
        this.fileListData.list = []
      } else {
        this.isSearch = true
        this.requestParam.p_project_dir_id = ''
        this.requestParam.tag_id = ''
        this.getProjectFileList()
      }
    },
    // 重置搜索条件
    reset () {
      this.requestParam.file_alias = ''
      this.isSearch = false
      this.fileListData.list = []
    },
    // 编辑文件标签
    editFileTag (row) {
      this.fileSign = row.file_sign
      this.choosedFile = row
      this.editTagDialogVisible = true
    },
    //
    editTagCb (data) {
      this.getProjectFileList()
    },
    // checkbox变化事件
    selectChange (cheecked, row) {
      // 当选中时，将文件id与值存入map中，反之则删除
      let choosedList = []
      if (cheecked) {
        this.fileIdMap.set(row.p_project_doc_file_id, row)
      } else {
        this.fileIdMap.delete(row.p_project_doc_file_id)
      }
      this.fileIdMap.forEach((value, key) => {
        choosedList.push(value)
      })
      this.choosedFileList = choosedList
      this.$emit('update:choosedList', choosedList)
      console.log(choosedList, 'select change')
    },
    //视频预览
    lookFile (row) {
      let isDocFile = ['docx', 'doc'].includes(row.file_ext) || false;//是否为word文本
      let isExcelFile = ['xls', 'xlsx'].includes(row.file_ext) || false;//是否为excel文本
      let isImg = ['jpg', 'jpeg', 'png'].includes(row.file_ext) || false;//是否为图片
      if (isDocFile == false && isExcelFile == false && isImg == false) {//视频
        this.dialogvideo = true;//视频
        this.videoUrl = row.file_address;
      } else if ((isDocFile == true || isExcelFile == true) && isImg == false) {//doc、excel在线预览
        let docUrl = row.file_address;
        let url = encodeURIComponent(docUrl)
        let officeUrl = 'http://view.officeapps.live.com/op/view.aspx?src=' + url;//在线预览
        // 在新窗口打开编码后 的链接
        window.open(officeUrl, '_blank')
      } else {
        this.url = row.file_address;
        this.viewDialog = true;
      }
    },
    // 编辑文件名
    editFile (row) {
      // 保存文件名，取消编辑的时候重置
      row.file_alias_temp = row.file_alias
      row.edit = true
    },
    // 取消编辑
    cancelEdit (row) {
      row.file_alias = row.file_alias_temp
      row.edit = false
    },
    // 确认编辑
    confirmEdit (row) {
      if (row.file_alias === '') {
        this.$message.warning('请输入文件名')
      } else {
        ProjectFileApi.updateProjectFile({
          data: {
            id: row.p_project_doc_file_id,
            file_alias: row.file_alias
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('修改文件名成功')
            row.edit = false
            this.getProjectFileList()
          }
        })
      }
    },
    // 下载文件
    downloadFile (row) {
      let url = row.file_address
      var alink = document.createElement('a')
      alink.href = url
      alink.target = '_blank'
      alink.download = ''
      alink.click()
    },
    // 删除文件确认
    deleteFile (row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteFileApi([row.p_project_doc_file_id])
        })
        .catch(() => { })
    },
    // 删除文件接口
    deleteFileApi (ids) {
      ProjectFileApi.deleteProjectFile({
        data: {
          file_ids: ids
        }
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除文件成功')
          this.getProjectFileList()
        }
      })
    },
    // 批量删除
    batchDelete () {
      // let selection = this.$refs.fileTable.selection
      let selection = this.choosedFileList
      let list = []
      if (selection.length > 0) {
        selection.map(item => {
          list.push(item.p_project_doc_file_id)
        })
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.deleteFileApi(list)
          })
          .catch(() => { })
      } else {
        this.$message.warning('请选择需要删除的文件')
      }
    },
    // 批量下载
    batchDownload () {
      // let selection = this.$refs.fileTable.selection
      let selection = this.choosedFileList
      if (selection.length > 0) {
        for (let i = 0; i < selection.length; i++) {
          let item = selection[i]
          // let file = new File([item.file_address],item.file_alias)
          // let file = new File(["Hello, world!"], "hello world.txt",)
          // FileSaver.saveAs(file)
          // FileSaver.saveAs(item.file_address, item.file_alias)
          let url = item.file_address
          var alink = document.createElement('a')
          alink.href = url
          alink.target = '_blank'
          alink.download = item.file_alias
          alink.click()
        }
      } else {
        this.$message.warning('请选择需要下载的文件')
      }
    },
    // 点击右上角的×关闭时，只清空队列，不调用新增
    uploadDialogClose () {
      this.uploadQuene = []
      this.$refs.uploadFile.clearFiles()
      this.uploadQueneDialogVisible = false
    },
    // 关闭上传文件弹框,清空队列,调用文件列表新增接口
    closeDialog () {
      this.createProjectFile()
      this.$refs.uploadFile.clearFiles()
      this.uploadQueneDialogVisible = false
    },
    // 上传文件
    uploadFile (file) {
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: process.env.bucket
      })
      let address = 'projectFile/' + this.choosedTreeNode.path + file.file.name
      client
        .multipartUpload(address, file.file, {
          progress: percent => {
            // this.$set(this.uploadQuene[this.uploadFileIndex], 'percent', parseInt(percent * 100) + '%')
            this.uploadQuene[this.uploadFileIndex].percent =
              parseInt(percent * 100) + '%'
            console.log(percent, 'percent')
          }
        })
        .then(res => {
          // data.attach = 'http://dev-consult-new.oss-cn-hangzhou.aliyuncs.com/' + res.name
          this.uploadQuene[this.uploadFileIndex].status = 'resolve'
          this.uploadQuene[this.uploadFileIndex].file_address = res.res.requestUrls[0].split('?')[0]
          this.uploadFileIndex++
          this.uploadFileQuene()
          console.log(res, this.uploadQuene, '111')
        })
    },
    handleFileChange (file, filelist) {
      if (this.choosedTreeNode.p_project_dir_id) {
        // 简易版debounce，以最后一次为准
        clearTimeout(this.timerId)
        this.timerId = setTimeout(() => {
          // elementui 上传组件会把filelist中所有status为ready的数据上传，
          // 因此首先把所有数据的status置为waiting，然后依次把status置为ready，实现队列效果
          filelist.map(item => {
            item.file_alias = item.name
            item.file_ext = item.name.split('.')[1]
            item.file_size = (item.size / (1024 * 1024)).toFixed(2) + 'M'
            item.status = 'waiting'
            this.$set(item, 'percent', '0%')
          })
          this.uploadQuene = filelist
          this.uploadFileIndex = 0
          this.uploadQueneDialogVisible = true
          // 控制文件一个个上传
          this.uploadFileQuene()
        }, 300)
      } else {
        this.$message.warning('请选择文件夹')
      }
    },
    // 通过队列的方式上传
    uploadFileQuene () {
      // console.log(this.uploadQuene, 'quene')
      if (this.uploadFileIndex < this.uploadQuene.length) {
        this.uploadQuene[this.uploadFileIndex].status = 'ready'
        this.$refs.uploadFile.submit()
      }
    },
    handleFileSuccess () { },
    beforeFileUpload (file) {
      console.log(file, 'before upload')
    },
    // 文件超出数量限制钩子函数
    handleFileExceed (file, filelist) {
      if (file.length > 20) {
        this.$message.warning('最多同时上传20个文件')
      }
      console.log(file, filelist, 'file exceed')
    },
    // 获取项目文档树
    getProjectFileTree () {
      // 当前用户为项目方时，传单位id，为中建协时，则不传
      // let companyId = ''
      // let userInfo = window.localStorage.getItem('userInfo') || '{}'
      // userInfo = JSON.parse(userInfo)
      // companyId = userInfo.comp_id
      ProjectFileApi.getFileTree({
        params: {
          project_ids: this.choosedProject.project_id
        }
      }).then(res => {
        if (res.code === 0) {
          // let obj = {
          //   p_project_dir_id: 0,
          //   dir_name: '项目xxx',
          //   children_list: res.data.list
          // }
          this.$store.dispatch('setProjectFileTree', res.data.list)
        }
      })
    },
    // 获取文件夹下文件列表
    getProjectFileList () {
      ProjectFileApi.getProjectFileList({
        params: this.requestParam
      }).then(res => {
        if (res.code === 0) {
          let data = res.data
          data.list.map(item => {
            this.$set(item, 'edit', false)

            if (this.fileIdMap.get(item.p_project_doc_file_id)) {
              this.$set(item, 'checked', true)
            } else {
              this.$set(item, 'checked', false)
            }
          })
          this.fileListData = data
        }
      })
    },
    // 文件列表-新增
    createProjectFile () {
      ProjectFileApi.createProjectFile({
        data: {
          file_params: this.uploadQuene,
          p_project_dir_id: this.choosedTreeNode.p_project_dir_id
        }
      }).then(res => {
        if (res.code === 0) {
          this.getProjectFileList()
        }
      })
    },
    // 编辑树形节点回调，重新获取数据，刷新树形
    editNodeCb () {
      this.getProjectFileTree()
    }

  },
  created () {
    let store = this.$store.state.choosedProject
    let local = window.localStorage.getItem('choosedProject') || '{}'
    this.choosedProject = store.project_id ? store : JSON.parse(local)
    this.getProjectFileTree()
  },
  mounted () { }
}
</script>
<style scoped lang="scss">
.project-file-container {
  background-color: #fff;
  height: 100%;
  h2 {
    width: 100%;
    height: 54px;
    line-height: 54px;
    color: #1441b3;
    font-size: 16px;
    padding-left: 20px;
    border-bottom: 1px solid #d9d9d9;
  }
  i {
    font-style: normal;
  }
  .tip {
    font-size: 12px;
    color: #999;
    margin-top: 20px;
  }
  .content {
    padding: 20px;
    .btn-group {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;

      .edit-btn {
        display: flex;
        justify-content: flex-start;
        .el-button {
          margin-right: 20px;
        }
        .download {
          border: 1px solid #52c41a;
          color: #52c41a;
        }
        .delete {
          border: 1px solid #bfbfbf;
          color: #333;
          margin-left: 0;
        }
      }
      .search-btn {
        display: flex;
        justify-content: flex-end;
        .el-input {
          width: 280px;
          margin-right: 10px;
        }
        // .el-button {
        //   width: 55px;
        //   background-color: #1890ff;
        //   color: #fff;
        //   border-top-left-radius: 0;
        //   border-bottom-left-radius: 0;
        // }
      }
      .span {
        color: #999;
        font-size: 12px;
      }
    }
    .file-content {
      // display: flex;
      // justify-content: space-between;
      position: relative;
      margin-top: 15px;
      min-height: 550px;
      height: 100%;
      .tree-container {
        width: 370px;
        padding-right: 20px;
        border-right: 1px solid #d9d9d9;
        position: absolute;
        left: 0;
        .tab-btn-container {
          width: 100%;
          height: 36px;
          display: flex;
          .tab-btn {
            flex: 1;
            height: 36px;
            font-size: 14px;
            color: #666;
            text-align: center;
            line-height: 36px;
            border-radius: 4px;
            border: 1px solid #bfbfbf;
            background-color: #fff;
            cursor: pointer;
            &.dir {
              border-right: 0;
              border-top-right-radius: 0;
              border-bottom-right-radius: 0;
            }
            &.tag {
              border-left: 0;
              border-top-left-radius: 0;
              border-bottom-left-radius: 0;
            }
            &.active {
              background-color: #1890ff;
              color: #fff;
            }
          }
        }
      }
      .table-container {
        // flex: 1 1 auto;
        position: absolute;
        left: 370px;
        right: 0;
        padding-left: 20px;
        height: 500px;
        overflow-y: scroll;
        // 表格内部编辑文件名图表样式
        .edit-input {
          .icon-container {
            position: absolute;
            width: 45px;
            height: 35px;
            display: flex;
            right: 12px;
            top: 15px;
            justify-content: space-around;
            align-items: center;
            background-color: #fff;
            i {
              font-size: 18px;
              cursor: pointer;
              &.cancel {
                color: #666;
              }
              &.confirm {
                color: #52c41a;
              }
            }
          }
        }
      }
    }
  }
  .upload-quene-list {
    .upload-quene-item {
      width: 100%;
      height: 48px;
      border-bottom: 1px solid #e5e5e5;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-left: 40px;
      font-size: 14px;
      color: #666;

      &:first-child {
        border-top: 1px solid #e5e5e5;
      }

      .file-name {
        width: 260px;
        margin-right: 120px;
        display: flex;
        align-items: center;
        img {
          width: 24px;
          height: 24px;
          margin-right: 15px;
        }
      }

      .file-size {
        width: 60px;
        margin-right: 40px;
      }

      .dir-name {
        width: 100px;
        margin-right: 40px;
        color: #1890ff;
      }

      .status {
        color: #333;
        display: flex;
        align-items: center;

        i {
          color: #52c41a;
          margin-right: 8px;
        }
      }
    }
  }
}
.videoLoc {
  width: 100%;
  height: 100%;
}
</style>
